/**    
 * 文件名：WebPathUtil.java    
 *    
 * 版本信息：1.0    
 * 日期：Nov 5, 2011    
 * Copyright (c) 2010-2011 ESRI China (Beijing) Ltd. All rights reserved   
 * 版权所有    
 *    
 */
package com.webreport.utils;

import java.io.File;
import java.io.UnsupportedEncodingException;

public class WebPathUtil {

	private static String systemPath = null;

	private static String webinfPath = null;

	/**
	 * 返回工程路径，如C:/Tomcat6029/webapps/projectname/
	 */
	public static String getWebModulPath() {
		String ret = getWebinfPath();
		int cnt = ret.indexOf("/WEB-INF");
		if (cnt > -1)
			ret = ret.substring(0, cnt);
		ret +="/"; 
		return ret;
	}

	/**
	 * 返回系统路径，如C:/Tomcat6029/webapps/
	 */
	public static String getSystemPath() {
		if (systemPath == null) {
			String res = getWebinfPath();
			if (res.indexOf("WEB-INF/") > 0 && res.length() > 10) {
				res = res.substring(0, res.lastIndexOf("/", res.length() - 12))
						+ "/";
			}
			systemPath = res;
		}
		return systemPath;
	}
	
	/**
	 * 返回工程路径，如C:/Tomcat6029/webapps/projectname/WEB-INF/classes/
	 */
	public static String getWebClassesPath() {
		String ret = getWebinfPath();
		ret += "classes/";
		return ret;
	}

	/**
	 * 返回系统WEB-INF的路径，如C:/Tomcat6029/webapps/projectname/WEB-INF/
	 */
	public static String getWebinfPath() {
		if (webinfPath == null) {
			String res = null;
			WebPathUtil u = new WebPathUtil();
			String classname = u.getClass().getName().replace('.', '/')
					+ ".class";
			ClassLoader cl = u.getClass().getClassLoader();
			if (cl != null) {
				java.net.URL url = cl.getResource(classname);
				if (url != null) {
					String path = url.getFile();
					int fileStrPosition = path.indexOf("file:/");
					int begin = 0;
					int end = path.length();

					if (fileStrPosition >= 0)
						begin = fileStrPosition + 5;
					// 先判断是否是未打包文件
					end = path.indexOf("classes/" + classname);
					if (end < 0) {
						// 如果是在webModule下面的jar包
						end = path.indexOf("lib/");
						if (end < 0) {
							// 在普通目录下的jar包
							int tmpend = path.indexOf("!/");
							end = path.substring(0, tmpend).lastIndexOf("/");
						}
					}
					String rf = path.substring(begin, end);
					res = new File(rf).getAbsolutePath().replace('\\', '/')
							+ "/";
				}
			}
			try {
				webinfPath = java.net.URLDecoder.decode(res, "UTF-8");
			} catch (UnsupportedEncodingException ex) {
			}
		}
		return webinfPath;
	}
	
	public static void main(String[] args) {
		System.out.println(WebPathUtil.getWebinfPath());
		System.out.println(WebPathUtil.getWebModulPath());
		System.out.println(WebPathUtil.getSystemPath());
	}

}
